//
//  CourseListViewController.m
//  ZPIOSEducation
//
//  Created by 董伟1 on 17/1/10.
//  Copyright © 2017年 mini1. All rights reserved.
//

#import "CourseListViewController.h"
#import "CourseDetailCell.h"
#import "CommentTeacherViewController.h"
#import "HomeWorkDetailViewController.h"
#import "CourseListButtonCell.h"
#import "ManualSignViewController.h"
#import "QRCodeSignViewController.h"

#import "MJRefresh.h"

@interface CourseListViewController () <UITableViewDelegate,UITableViewDataSource>
{
    NSMutableArray  *dataArray;
    NSInteger  currentPage;
    BOOL  hasNextPage;
}

@property (weak, nonatomic) IBOutlet UITableView *mainTableView;

@end

@implementation CourseListViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    self.title = @"课表";
    [self.navigationController setNavigationBarHidden:NO animated:YES];
    [[NSNotificationCenter  defaultCenter] addObserver:self selector:@selector(refreshCourseList) name:@"refreshCourseList" object:nil];
    
    self.mainTableView.delegate = self;
    self.mainTableView.dataSource = self;
    
    dataArray = [[NSMutableArray  alloc] init];
    currentPage = 1;
    hasNextPage = NO;
    
    __weak CourseListViewController *weakSelf = self;
    [self.mainTableView  addLegendHeaderWithRefreshingBlock:^{
        [weakSelf  refreshCourseList];
    }];
    
    [self.mainTableView  addLegendFooterWithRefreshingBlock:^{
        [weakSelf  loadMoreData];
    }];
    
    [self  requestData];
    
}

- (void)refreshCourseList
{
    currentPage = 1;
    [self  requestData];
}

- (void)loadMoreData
{
    if (hasNextPage) {
        [self  requestData];
    }else {
        [self.mainTableView.footer endRefreshing];
    }
}

- (BOOL)isSameDate:(NSInteger)index
{
    NSDictionary  *lastDic = [dataArray  objectAtIndex:index - 1];
    NSString  *lastDate = [lastDic  objectForKey:@"dates"];
    NSString  *lastWeek = [lastDic  objectForKey:@"week"];
    NSDictionary  *currentDic = [dataArray  objectAtIndex:index];
    NSString  *currentDate = [currentDic  objectForKey:@"dates"];
    NSString  *currentWeek = [currentDic  objectForKey:@"week"];
    
    if ([lastDate isEqual:currentDate] && [lastWeek  isEqual:currentWeek]) {
        return YES;
    }else {
        return NO;
    }
}

- (void)requestData
{
    [self  showHudithString:@"加载中..."];
    NSMutableDictionary  *paramDic = [NSMutableDictionary  dictionaryWithObjectsAndKeys:[[ZPAuthStore  sharedZPAuthStore].userToDic  objectForKey:@"memberId"],@"teacherId",@"10",@"pagesize",[NSString  stringWithFormat:@"%ld",(long)currentPage],@"pagenumber", nil];

    [[ZPNetworking  sharedZPNetworking] POST:APIPPT@"teacher/getCourse.json" parameters:paramDic progress:^(NSProgress * _Nullable progress) {
        
    } success:^(id  _Nonnull responseObject) {
        NSLog(@"======%@",responseObject);
        [self  hiddenHud];
        if (self.mainTableView.header.isRefreshing) {
            [self.mainTableView.header  endRefreshing];
        }
        if (self.mainTableView.footer.isRefreshing) {
            [self.mainTableView.footer  endRefreshing];
        }
        
        if ([[responseObject  objectForKey:@"code"] integerValue] == 200) {
            
            if (currentPage == 1) {
                [dataArray  removeAllObjects];
            }
            if ([[[responseObject  objectForKey:@"result"] objectForKey:@"result"] isKindOfClass:[NSArray  class]]) {
                [dataArray  addObjectsFromArray:[[responseObject  objectForKey:@"result"] objectForKey:@"result"]];
            }
            [self.mainTableView  reloadData];
            
            if ([[[responseObject  objectForKey:@"result"] objectForKey:@"hasNextPage"] boolValue]) {
                currentPage ++;
                hasNextPage = YES;
            }else {
                hasNextPage = NO;
                [self.mainTableView.footer  noticeNoMoreData];
            }
            
            if (dataArray.count == 0) {
                [self  showNoDataViewWithTitle:@"暂无相关课程"];
            }else {
                [self  hiddenNoDataView];
            }
        }else {
            [ZPPromptView  showMessage:[responseObject  objectForKey:@"codeMsg"]];
        }
        
    } failure:^(NSError * _Nonnull error) {
        [self  hiddenHud];
        if (self.mainTableView.header.isRefreshing) {
            [self.mainTableView.header  endRefreshing];
        }
        if (self.mainTableView.footer.isRefreshing) {
            [self.mainTableView.footer  endRefreshing];
        }
    }];
}

#pragma mark cell内评价按钮 写作业按钮
- (void)cellTypeButtonClick:(id)sender
{
    UIButton  *tempBtn = (UIButton  *)sender;
    NSString  *titleStr = tempBtn.titleLabel.text;
    NSDictionary  *tempDic = [dataArray  objectAtIndex:tempBtn.tag];
    if ([titleStr  isEqualToString:@"扫码签到"]) {
        QRCodeSignViewController  *viewController = [[QRCodeSignViewController  alloc] initWithNibName:@"QRCodeSignViewController" bundle:nil];
        viewController.className = [NSString  stringWithFormat:@"%@",[tempDic  objectForKey:@"className"]];
        viewController.scheduleId = [NSString  stringWithFormat:@"%@",[tempDic  objectForKey:@"scheduleId"]];
        [self.navigationController  pushViewController:viewController animated:YES];
    }else if ([titleStr  isEqualToString:@"手动签到"]) {
        ManualSignViewController  *viewController = [[ManualSignViewController  alloc] initWithNibName:@"ManualSignViewController" bundle:nil];
        viewController.classNameStr = [NSString  stringWithFormat:@"%@",[tempDic  objectForKey:@"className"]];
        viewController.scheduleIdStr = [NSString  stringWithFormat:@"%@",[tempDic  objectForKey:@"scheduleId"]];
        [self.navigationController  pushViewController:viewController animated:YES];
    }
}

#pragma mark - UITableView Delegate
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return [dataArray  count];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    NSDictionary  *tempDic = [dataArray  objectAtIndex:section];
    if ([[tempDic  objectForKey:@"isButton"] integerValue] == 1) {
        return 2;
    }else {
        return 1;
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSInteger  section = [indexPath  section];
    NSInteger  row = [indexPath  row];
    if (row == 0) {
        if (section == 0) {
            return 130.;
        }else {
            if ([self isSameDate:section]) {
                return 90.;
            }else {
                return 130.;
            }
            
        }
    }else {
        return 61.;
    }
    
}

- (UITableViewCell  *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSInteger  section = [indexPath  section];
    NSInteger  row = [indexPath  row];
    NSDictionary  *tempDic = [dataArray  objectAtIndex:section];
    
    if (row == 0) {
        static NSString *CellIdentifier = @"CourseDetailCell";
        CourseDetailCell  *cell = (CourseDetailCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
        if (cell == nil) {
            cell = [[[NSBundle mainBundle] loadNibNamed:@"CourseDetailCell" owner:self options:nil] lastObject];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
        }
        
        NSInteger  color = [[tempDic  objectForKey:@"type"] integerValue];
        if (color == 0) {
            //灰色
            cell.leftView.backgroundColor = RGBACOLOR(249, 249, 249, 1.);
            cell.rightView.backgroundColor = RGBACOLOR(249, 249, 249, 1.);
            
            cell.startTimeLab.textColor = RGBACOLOR(205, 205, 205, 1.);
            cell.toLabel.textColor = RGBACOLOR(205, 205, 205, 1.);
            cell.endTimeLab.textColor = RGBACOLOR(205, 205, 205, 1.);
            cell.startTimeLab.textColor = RGBACOLOR(205, 205, 205, 1.);
            cell.classLab.textColor = RGBACOLOR(205, 205, 205, 1.);
            cell.classDetailLab.textColor = RGBACOLOR(205, 205, 205, 1.);
            cell.numLab.textColor = RGBACOLOR(205, 205, 205, 1.);
            
        }else {
            //黑色
            cell.leftView.backgroundColor = RGBACOLOR(247, 251, 255, 1.);
            cell.rightView.backgroundColor = RGBACOLOR(247, 251, 255, 1.);
            
            cell.startTimeLab.textColor = RGBACOLOR(51, 51, 51, 1.);
            cell.toLabel.textColor = RGBACOLOR(51, 51, 51, 1.);
            cell.endTimeLab.textColor = RGBACOLOR(51, 51, 51, 1.);
            cell.startTimeLab.textColor = RGBACOLOR(51, 51, 51, 1.);
            cell.classLab.textColor = RGBACOLOR(51, 51, 51, 1.);
            cell.classDetailLab.textColor = RGBACOLOR(153, 153, 153, 1.);
            cell.numLab.textColor = RGBACOLOR(51, 51, 51, 1.);
            
        }
        
        if (section == 0) {
            cell.dateLab.hidden = NO;
            cell.dateLab.text = [NSString  stringWithFormat:@"%@  %@",[tempDic  objectForKey:@"dates"],[tempDic  objectForKey:@"week"]];
        }else {
            if ([self  isSameDate:section]) {
                cell.dateLab.hidden = YES;
            }else {
                cell.dateLab.hidden = NO;
                cell.dateLab.text = [NSString  stringWithFormat:@"%@  %@",[tempDic  objectForKey:@"dates"],[tempDic  objectForKey:@"week"]];
            }
        }
        
        cell.startTimeLab.text = [NSString  stringWithFormat:@"%@",[tempDic  objectForKey:@"startTime"]];
        cell.endTimeLab.text = [NSString  stringWithFormat:@"%@",[tempDic  objectForKey:@"endTime"]];
        cell.classLab.text = [NSString  stringWithFormat:@"%@",[tempDic  objectForKey:@"className"]];
        cell.classDetailLab.text = [NSString  stringWithFormat:@"%@     %@",[tempDic  objectForKey:@"classroomName"],[tempDic  objectForKey:@"teacherName"]];
        cell.numLab.text = [NSString  stringWithFormat:@"%@",[tempDic  objectForKey:@"progress"]];
        
        return cell;
        
    }else {
        static NSString *CellIdentifier = @"CourseListButtonCell";
        CourseListButtonCell  *cell = (CourseListButtonCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
        if (cell == nil) {
            cell = [[[NSBundle mainBundle] loadNibNamed:@"CourseListButtonCell" owner:self options:nil] lastObject];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
        }
        
        UIView  *whiteView = (UIView  *)[cell.contentView  viewWithTag:1000];
        for (UIButton  *tempBtn in whiteView.subviews) {
            [tempBtn  removeFromSuperview];
        }
        for (int i = 0; i < 2; i ++) {
            UIButton  *button = [UIButton  buttonWithType:UIButtonTypeCustom];
            button.frame = CGRectMake(SCREENWIDTH - 11 - 80 * 2 + 80 * i, 12, 70, 30);
            [button  setTitleColor:[UIColor  whiteColor] forState:UIControlStateNormal];
            [button.titleLabel  setFont:[UIFont  systemFontOfSize:12.]];
            button.layer.masksToBounds = YES;
            button.layer.cornerRadius = 4.;
            [button  setBackgroundColor:RGBACOLOR(33, 164, 235, 1.)];
            if (i == 0) {
                [button  setTitle:@"扫码签到" forState:UIControlStateNormal];
            }else if (i == 1) {
                [button  setTitle:@"手动签到" forState:UIControlStateNormal];
            }
            button.tag = section;
            [button  addTarget:self action:@selector(cellTypeButtonClick:) forControlEvents:UIControlEventTouchUpInside];
            [whiteView  addSubview:button];
            
        }
        
        return cell;
    }
    
}

- (void)dealloc
{
    [[NSNotificationCenter  defaultCenter] removeObserver:self name:@"refreshCourseList" object:nil];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
